from django.db import models
from django.contrib.auth import get_user_model
from cmdb.models import Host
import uuid

User = get_user_model()


class SSHSession(models.Model):
    """SSH会话模型"""
    session_id = models.UUIDField(default=uuid.uuid4, unique=True, verbose_name='会话ID')
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户')
    host = models.ForeignKey(Host, on_delete=models.CASCADE, verbose_name='主机')

    # 连接信息
    client_ip = models.GenericIPAddressField(verbose_name='客户端IP')
    user_agent = models.TextField(blank=True, null=True, verbose_name='用户代理')

    # 会话状态
    status = models.CharField(max_length=20, default='connecting', verbose_name='状态', choices=[
        ('connecting', '连接中'),
        ('connected', '已连接'),
        ('disconnected', '已断开'),
        ('error', '错误')
    ])

    # 时间信息
    start_time = models.DateTimeField(auto_now_add=True, verbose_name='开始时间')
    end_time = models.DateTimeField(null=True, blank=True, verbose_name='结束时间')
    last_activity = models.DateTimeField(auto_now=True, verbose_name='最后活动时间')

    # 会话统计
    command_count = models.IntegerField(default=0, verbose_name='命令数量')
    bytes_sent = models.BigIntegerField(default=0, verbose_name='发送字节数')
    bytes_received = models.BigIntegerField(default=0, verbose_name='接收字节数')

    # 终端配置
    terminal_width = models.IntegerField(default=80, verbose_name='终端宽度')
    terminal_height = models.IntegerField(default=24, verbose_name='终端高度')

    # 录制配置
    is_recorded = models.BooleanField(default=True, verbose_name='是否录制')
    recording_path = models.CharField(max_length=500, blank=True, null=True, verbose_name='录制文件路径')

    class Meta:
        db_table = 'ssh_session'
        verbose_name = 'SSH会话'
        verbose_name_plural = 'SSH会话'
        ordering = ['-start_time']
        indexes = [
            models.Index(fields=['user', '-start_time']),
            models.Index(fields=['host', '-start_time']),
            models.Index(fields=['status']),
        ]

    def __str__(self):
        return f"{self.user.username}@{self.host.hostname} ({self.session_id})"

    @property
    def duration(self):
        """会话持续时间"""
        if self.end_time:
            return self.end_time - self.start_time
        return None

    @property
    def is_active(self):
        """是否活跃"""
        return self.status in ['connecting', 'connected']


class SSHCommand(models.Model):
    """SSH命令记录模型"""
    session = models.ForeignKey(SSHSession, on_delete=models.CASCADE, related_name='commands', verbose_name='会话')
    command = models.TextField(verbose_name='命令')
    output = models.TextField(blank=True, null=True, verbose_name='输出')
    exit_code = models.IntegerField(null=True, blank=True, verbose_name='退出码')

    # 时间信息
    start_time = models.DateTimeField(auto_now_add=True, verbose_name='开始时间')
    end_time = models.DateTimeField(null=True, blank=True, verbose_name='结束时间')
    duration = models.FloatField(null=True, blank=True, verbose_name='执行时间(秒)')

    # 命令分类
    command_type = models.CharField(max_length=50, blank=True, null=True, verbose_name='命令类型')
    is_dangerous = models.BooleanField(default=False, verbose_name='是否危险命令')

    class Meta:
        db_table = 'ssh_command'
        verbose_name = 'SSH命令'
        verbose_name_plural = 'SSH命令'
        ordering = ['-start_time']
        indexes = [
            models.Index(fields=['session', '-start_time']),
            models.Index(fields=['command_type']),
            models.Index(fields=['is_dangerous']),
        ]

    def __str__(self):
        return f"{self.session.user.username}: {self.command[:50]}"


class SSHConnectionPool(models.Model):
    """SSH连接池模型"""
    host = models.ForeignKey(Host, on_delete=models.CASCADE, verbose_name='主机')
    connection_id = models.UUIDField(default=uuid.uuid4, unique=True, verbose_name='连接ID')

    # 连接状态
    is_active = models.BooleanField(default=True, verbose_name='是否活跃')
    last_used = models.DateTimeField(auto_now=True, verbose_name='最后使用时间')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    # 连接统计
    use_count = models.IntegerField(default=0, verbose_name='使用次数')
    error_count = models.IntegerField(default=0, verbose_name='错误次数')

    class Meta:
        db_table = 'ssh_connection_pool'
        verbose_name = 'SSH连接池'
        verbose_name_plural = 'SSH连接池'
        ordering = ['-last_used']

    def __str__(self):
        return f"{self.host.hostname} - {self.connection_id}"
